package com.int_tech.timeTask194;

import com.int_tech.MessageCodeAll.dao.CodeA0Dao;
import com.int_tech.MessageCodeAll.dao.CodeA0NewDao;
import com.int_tech.MessageCodeAll.dao.CodeA2DoubleDao;
import com.int_tech.MessageCodeAll.entity.CodeA0New;
import com.int_tech.MessageCodeAll.entity.CodeA2;
import com.int_tech.MessageCodeAll.entity.CodeA2Double;
import com.int_tech.car.dao.CarDao;
import com.int_tech.mession.dao.MessionDao;
import com.int_tech.mession.entity.Mession;
import com.int_tech.station.dao.StationDao;
import com.int_tech.utils.DateTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

/**
 * Created by liubochao on 2018/8/4.
 */
@Component
public class CreateNewMessionTimeTask {

    @Autowired
    private CodeA0NewDao codeA0NewDao;

    @Autowired
    private MessionDao messionDao;

    @Autowired
    private CodeA2DoubleDao codeA2DoubleDao;

    @Autowired
    private CarDao carDao;

    @Autowired
    private StationDao stationDao;

    @Autowired
    private CodeA0Dao codeA0Dao;

    @Scheduled(cron="0/10 * * * * ?")
    public void checkA0() throws ParseException {

        //每次遍历100条
        PageRequest pageRequest = new PageRequest(0, 500);
//        Page<CodeA0New> codeA0NewPage = codeA0NewDao.findByCheckStatusAndCarNumber(pageRequest, 0, "010AFY891");
//        Page<CodeA0New> codeA0NewPage = codeA0NewDao.findByCheckStatusAndStatus(pageRequest, 0, 0);
        Date date = DateTool.string2Date("2018-07-23 00:00:00","yyyy-MM-dd HH:mm:ss");
        Page<CodeA0New> codeA0NewPage = codeA0NewDao.findByCheckStatusAndStatusAndCreatedTimeAfter(pageRequest, 0, 0,date);
        List<CodeA0New> codeA0NewList = codeA0NewPage.getContent();

        for(CodeA0New codeA0New : codeA0NewList)
        {
            try {
                codeA0New.setCheckStatus(2);
                codeA0NewDao.save(codeA0New);

                //规则变为A0前面如果再与前一个A0之间有符合要求的开关门，创建任务单，如果前面有任务单，前一个任务单结束

                PageRequest pageRequest1 = new PageRequest(0, 1);
                Page<CodeA2Double> codeA2DoublePage = codeA2DoubleDao.findByctBeforeAndOpenStatusAndTimePlus(codeA0New.getCarNumber(),codeA0New.getCreatedTime(),1,180,pageRequest1);
                List<CodeA2Double> codeA2DoubleList2 = codeA2DoublePage.getContent();

                if(codeA2DoubleList2 == null || codeA2DoubleList2.size() == 0)
                {
                    //没有符合要求的
                    codeA0New.setCheckStatus(-22);
                    codeA0NewDao.save(codeA0New);
                    continue;
                }
                else
                {
                    //之前的关门
                    CodeA2Double codeA2DoubleClose = codeA2DoubleList2.get(0);

                    //判定这个关门数据前一条的开门数据
                    codeA2DoublePage = codeA2DoubleDao.findByctBeforeAndOpenStatus(codeA2DoubleClose.getCarNumber(),codeA2DoubleClose.getCreatedTime(),0,pageRequest1);
                    codeA2DoubleList2 = codeA2DoublePage.getContent();

                    if(codeA2DoubleList2 == null || codeA2DoubleList2.size() == 0)
                    {
                        //没有符合要求的开门与其配对
                        codeA0New.setCheckStatus(-33);
                        codeA0NewDao.save(codeA0New);
                        continue;
                    }
                    else
                    {
                        //有配对的开门，需要校验开门时间是否大于上一次任务单的时间
                        CodeA2Double codeA2DoubleOpen = codeA2DoubleList2.get(0);

                        //查询上一个任务单
                        Page<Mession> messionPage = messionDao.findByCarNumberAndCreateTimeBeforeAndYiChangOrderByCreateTimeDesc(pageRequest1,codeA0New.getCarNumber(),codeA0New.getCreatedTime(),0);
                        List<Mession> messionList = messionPage.getContent();


                        //如果就没有上一个订单，可以直接添加了
                        if(messionList == null || messionList.size() == 0)
                        {
                            Mession mession = new Mession();

                            mession.setCreateTime(codeA0New.getCreatedTime());
                            mession.setIsOver(0);
                            mession.setIsAnsyCarTime(0);
                            mession.setYiChang(0);
                            mession.setCarNumber(codeA0New.getCarNumber());
                            mession.setRate(codeA0New.getRate());
                            mession.setRateDataString(codeA0New.getRateDateString());
                            mession.setLat(codeA0New.getLat());
                            mession.setLng(codeA0New.getLng());

                            //查询最大任务递增码
                            //车牌区号
                            String areaNumber = codeA0New.getCarNumber().substring(0,3);

                            String time = DateTool.Date2String(codeA0New.getCreatedTime(),"yyyyMMddHHmmss");
                            time = time.substring(0, 8);

                            int todayCount = messionDao.countByMessionNumberLike(time);

                            int thisCount = todayCount + 1;

                            String maxCode = String.valueOf(thisCount);


                            if(thisCount < 10)
                            {
                                maxCode = "000"+String.valueOf(maxCode);
                            }
                            else if(thisCount < 100)
                            {
                                maxCode = "00"+String.valueOf(maxCode);
                            }
                            else if(thisCount < 1000)
                            {
                                maxCode = "0"+ String.valueOf(maxCode);
                            }


                            String messionNumber = areaNumber+time+maxCode;

                            mession.setMessionNumber(messionNumber);

                            mession.setStartOpenDoorTime(codeA2DoubleOpen.getCreatedTime());
                            mession.setStartCloseDoorTime(codeA2DoubleClose.getCreatedTime());
                            mession.setStartAddress(codeA2DoubleClose.getLocation());

                            messionDao.save(mession);

                        }
                        else
                        {
                            //如果上一个任务单的创建时间在open之前，可以直接添加了
                            Mession lastMession = messionList.get(0);
                            if(lastMession.getCreateTime().before(codeA2DoubleOpen.getCreatedTime()))
                            {
                                Mession mession = new Mession();

                                mession.setCreateTime(codeA0New.getCreatedTime());
                                mession.setIsOver(0);
                                mession.setIsAnsyCarTime(0);
                                mession.setYiChang(0);
                                mession.setCarNumber(codeA0New.getCarNumber());
                                mession.setRate(codeA0New.getRate());
                                mession.setRateDataString(codeA0New.getRateDateString());
                                mession.setLat(codeA0New.getLat());
                                mession.setLng(codeA0New.getLng());

                                //查询最大任务递增码
                                //车牌区号
                                String areaNumber = codeA0New.getCarNumber().substring(0,3);

                                String time = DateTool.Date2String(codeA0New.getCreatedTime(),"yyyyMMddHHmmss");
                                time = time.substring(0, 8);

                                int todayCount = messionDao.countByMessionNumberLike(time);

                                int thisCount = todayCount + 1;

                                String maxCode = String.valueOf(thisCount);


                                if(thisCount < 10)
                                {
                                    maxCode = "000"+String.valueOf(maxCode);
                                }
                                else if(thisCount < 100)
                                {
                                    maxCode = "00"+String.valueOf(maxCode);
                                }
                                else if(thisCount < 1000)
                                {
                                    maxCode = "0"+ String.valueOf(maxCode);
                                }


                                String messionNumber = areaNumber+time+maxCode;

                                mession.setMessionNumber(messionNumber);

                                mession.setStartOpenDoorTime(codeA2DoubleOpen.getCreatedTime());
                                mession.setStartCloseDoorTime(codeA2DoubleClose.getCreatedTime());
                                mession.setStartAddress(codeA2DoubleClose.getLocation());

                                messionDao.save(mession);

                                //结束上一个订单
                                lastMession.setIsOver(1);

                                lastMession.setEndOpenDoorTime(mession.getStartOpenDoorTime());
                                lastMession.setEndCloseDoorTime(mession.getStartCloseDoorTime());
                                lastMession.setEndAddress(mession.getStartAddress());

                                messionDao.save(lastMession);


                                //如果上一个订单的起点终点相同，不做为任务单
                                if(lastMession.getStartAddress().equals(lastMession.getEndAddress()))
                                {
                                    lastMession.setIsOver(2);
                                    messionDao.save(lastMession);
                                }



                                /*//寻找上一个订单的卸车开关门
                                codeA2DoublePage = codeA2DoubleDao.findByctAfterAndOpenStatusAndTimePlus(codeA0New.getCarNumber(),lastMession.getCreateTime(),1,180,pageRequest1);
                                codeA2DoubleList2 = codeA2DoublePage.getContent();

                                CodeA2Double codeA2DoubleEndClose = codeA2DoubleList2.get(0);


                                codeA2DoublePage = codeA2DoubleDao.findByctBeforeAndOpenStatus(codeA0New.getCarNumber(),codeA2DoubleEndClose.getCreatedTime(),0,pageRequest1);
                                codeA2DoubleList2 = codeA2DoublePage.getContent();

                                CodeA2Double codeA2DoubleEndOpen = codeA2DoubleList2.get(0);

                                lastMession.setEndOpenDoorTime(codeA2DoubleEndOpen.getCreatedTime());
                                lastMession.setEndCloseDoorTime(codeA2DoubleEndClose.getCreatedTime());
                                lastMession.setEndAddress(codeA2DoubleEndOpen.getLocation());*/

                            }
                            else
                            {
                                codeA0New.setCheckStatus(-33);
                                codeA0NewDao.save(codeA0New);
                                continue;
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
                codeA0New.setCheckStatus(-2);
                codeA0NewDao.save(codeA0New);
            }
        }
    }


    /**
     * 任务单重复更新
     * @throws ParseException
     */
//    @Scheduled(cron="0 0/20 * * * ?")
    public void checkMession() throws ParseException {


        List<Mession> messionList = messionDao.findByIsOverAndCheckStatus(1,0);


        for(Mession mession : messionList)
        {
            if(mession.getId() == 90274)
            {
                System.out.print(111);
            }
            if(mession.getRateDataString().contains("2128,2186,1569,2289,1989,1081,1211,2058,1833,1916,1787,1753"))
            {
                 System.out.print(11111);
            }
            if(mession.getRateDataString().contains("2424,2320,2055,2344,2174,1457,2279,2265,2147,2306,2142,1793"))
            {
                System.out.print(11111);
            }
            mession.setCheckStatus(1);
            messionDao.save(mession);


            //查询上一个任务单
            PageRequest pageRequest1 = new PageRequest(0, 1);
            Page<Mession> messionPage = messionDao.findByCarNumberAndCreateTimeBeforeAndYiChangOrderByCreateTimeDesc(pageRequest1,mession.getCarNumber(),mession.getCreateTime(),0);
            List<Mession> messionPageList = messionPage.getContent();

            Mession lastMession = new Mession();

            if(messionPageList == null || messionPageList.size() == 0)
            {

            }
            else
            {
                lastMession = messionPageList.get(0);

                //这个任务单与上一个任务单相差小于3，只替换卸车信息，否则装载率也替换
                Double ratePlus = Double.parseDouble(lastMession.getRate()) - Double.parseDouble(mession.getRate());
                if(ratePlus > 3 || ratePlus < -3)
                {
//                    //替换装载率
//                    lastMession.setRate(mession.getRate());
//                    lastMession.setRateDataString(mession.getRateDataString());
//                    lastMession.setEveryRate(mession.getEveryRate());
                    double distance = getDistance(lastMession.getLat(),lastMession.getLng(),mession.getLat(),mession.getLng());

                    if(distance > 500 || distance < -500)
                    {

                    }
                    else
                    {
                        lastMession.setRate(mession.getRate());
                        lastMession.setRateDataString(mession.getRateDataString());
                        lastMession.setEveryRate(mession.getEveryRate());

                        lastMession.setEndOpenDoorTime(mession.getEndOpenDoorTime());
                        lastMession.setEndCloseDoorTime(mession.getEndCloseDoorTime());
                        if(!(mession.getEndAddress().indexOf("场站外")!=-1))
                        {
                            lastMession.setEndAddress(mession.getEndAddress());
                        }

                        lastMession.setCheckStatus(1);
                        messionDao.save(lastMession);

                        mession.setCheckStatus(-88);
                        messionDao.save(mession);
                    }
                }
                else
                {
                    if(!(mession.getEndAddress().indexOf("场站外")!=-1))
                    {
                        lastMession.setEndOpenDoorTime(mession.getEndOpenDoorTime());
                        lastMession.setEndCloseDoorTime(mession.getEndCloseDoorTime());
                        lastMession.setEndAddress(mession.getEndAddress());
                    }

                    messionDao.save(lastMession);

                    mession.setCheckStatus(-99);
                    messionDao.save(mession);
                }
            }
        }
    }


    //地球平均半径
    private static final double EARTH_RADIUS = 6378137;
    //把经纬度转为度（°）
    private static double rad(double d){
        return d * Math.PI / 180.0;
    }

    public static double getDistance(String lng1, String lat1, String lng2, String lat2){
        double radLat1 = rad(Double.parseDouble(lat1));
        double radLat2 = rad(Double.parseDouble(lat2));
        double a = radLat1 - radLat2;
        double b = rad(Double.parseDouble(lng1)) - rad(Double.parseDouble(lng2));
        double s = 2 * Math.asin(
                Math.sqrt(
                        Math.pow(Math.sin(a/2),2)
                                + Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)
                )
        );
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        return s;
    }
}
